JZ25 复杂链表的复制
https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
import java.util.HashMap;
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
if (pHead == null) return null;
HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode result = new RandomListNode(pHead.label);
RandomListNode cur = pHead;
RandomListNode p = result;
while(pHead != null) {
map.put(pHead, new RandomListNode(pHead.label));
pHead = pHead.next;
}
// target作为新链表的头,由cur,p移动来复制链表
while (cur != null) {
p.next = map.get( cur.next );
p.random = map.get( cur.random );
cur = cur.next;
p = p.next;
}
return result;
}
}